# coding = utf-8
# 该文件主要负责消息关键字处理，且与上一层工具文件建立 关键字<->功能 上的联系
# 关键字处理就是生成符合参数规范的参数列表，来调用一个或多个功能函数
# 我还有什么作业没有完成？ --> tools(**{q_number, ...}) --> 你压根麻子都没有写！
import re
import time

from .views_tools import *

task_patten = re.compile(r'''..任务：(?P<name>.*?)\W
结束时间：(?P<end>.*?)\W
提交至：(?P<send_to>.*?)\W
压缩包命名：(?P<re_name>.*?)\W
命名模板：(?P<pattern>.*?)\W
文件类型：(?P<type_of_content>.*?)\W
任务描述：(?P<describe>.*)''', re.X | re.S)  # 开始时间：(?P<begin>.*?)\W   原来在第二行

login_patten = re.compile(r'''姓名：(?P<name>.*?)\W
班级：.*(?P<class_number>\d{4}).*
学号：(?P<id_number>\d{10})''', re.X | re.S)

tip_patten = re.compile(r'''创建提醒：(?P<name>.*?)\W
提醒时间：(?P<begin>.*?)\W
提醒方式：(?P<method>\d{1}).*\W
提醒内容：(?P<text>.*)''', re.X | re.S)

help_patten = re.compile(r'''(?:(?:帮助：)|(?:help：))(?P<option>.*)''', re.X | re.S)

statistics_patten = re.compile(r'''：(.*)''', re.X | re.S)


@log_decorator
def begging(src_body) -> dict:
    """
    数据整理
    将有用的数据转化为可以用的形式
    将文本提取当命令备用，提取文件链接、图片链接备用，提取QQ号备用
    type: image, file, text, other(图片消息混合)
    """
    src = json.loads(src_body)
    text = ''
    files = dict()
    imgs = list()
    q_number = ''
    is_group = False
    type_ = ''
    if 'file' in src:
        for i in src.keys():
            if i == 'file':
                files[src[i]['name']] = {'size': src[i]['size'], 'url': src[i]['url']}
        q_number = src['user_id']
        type_ = 'file'
    else:
        temp = src['message']
        for i in range(len(temp)):
            if temp[i]['type'] == 'image':
                imgs.append(temp[i]['data']['url'])
                type_ = 'image' if type_ == '' or type_ == 'image' else 'other'
            elif temp[i]['type'] == 'text':
                text += '|' + temp[i]['data']['text']
                type_ = 'text' if type_ == '' or type_ == 'text' else 'other'
        q_number = src['sender']['user_id']
        is_group = bool(src['message_type'] != 'private')
        if is_group:
            is_group = src['group_id']
    return {'q_number': q_number, 'imgs': imgs, 'files': files, 'text': text, 'is_group': is_group, 'type': type_}


# @log_decorator
def filter_order(data):
    if data['is_group']:
        # 群发的报数任务
        text = data.get('text', '')
        text = text.strip('|')  # .split('|')  ‘|’服务于多段命令，由于该命令在报数中几乎没有，所以，，，
        if is_root(data['q_number']):
            if '开始报数：' in text or '全体成员' in text:  # 且这里默认为报数任务同一时间只存在一个
                talk(3222087513, f"在群{data.get('q_number')}@全体成员了！！！\n" + text)  # 喵″
            #     event = text.replace('：', ':')  # 以防查询时将：当命令
            #     status = create_statistic(event, data['q_number'])
            #     if status['status'] == 1:
            #         talk(q_number=data['q_number'], msg=status['error'])
            #         return
            #     talk(q_number=data['q_number'], msg='报数任务创建成功！群成员的[：消息]将被记录')
            #     return
            # if '提醒报数：' in text:  # 默认(没有消息)全部提醒(群/私)，否则1/0对应(群/私)
            #     remind_statistic(group_id=data['is_group'])
            #     return
            # if '查看报数：' in text:
            #     status = view_statistic()
            #     temp_msg = ''
            #     if status['status'] == 1:
            #         talk(data['is_group'], status['error'], group=True)
            #     else:
            #         for i, j in status['info'].items():
            #             temp_msg += f'报数为[{i}]的有：{j}\n'
            #         temp_msg += f'没有报数的人为：{status["not"]}' if status["not"] else '全部报完'
            #     talk(data['is_group'], temp_msg if temp_msg else '目前没有报数任务', group=True)
            #     return
            # if '停止报数：' in text:  # 记得在停止时将结果反馈一下，否则直接删了数据就丢了
            #     build_and_send_result()
            #     talk(data['is_group'], '报数停止，结果已用QQ邮箱反馈给任务创建者', group=True)
            #     drop_statistic()
            #     return
            # if '删除报数：' in text:  # 不反馈结果，直接删除
            #     drop_statistic()
            #     talk(data['is_group'], '不知道有没有报数，反正全删了:)', group=True)
            #     return
        temp_match = statistics_patten.match(text)
        if temp_match:  # 目前只创建单报数任务，日后如果冒号前有东西，那一定是任务名称，现在冒号前没有东西，所以是最近的报数任务
            # 冒号匹配冒号后面的内容作为保存内容，，，目前不想写匹配，，，所以只匹配后面的数字
            info = temp_match.groups()[0]
            statisticing(data['q_number'], info)
    else:
        # 私发的其他任务
        if 'help：' in data['text'].strip('|') or '帮助：' in data['text'].strip('|'):
            option_ = help_patten.search(data['text'].strip('|')).groupdict()['option']
            for i in get_orders(option_):
                talk(data['q_number'], i)
            return
        """
        分离命令，注册命令状态
        """
        if data.get('type') == 'file':  # 检查缓存命令集，看情况放入文件夹
            temp = cache.get(data['q_number'])
            if temp['status'] == 404:
                # 没有缓存，所以push缓存，询问这是什么文件,,,,,,,,,,,,,,,,,,,,,url&name
                file_name_and_url = list(data['files'].items())
                cache.push(data['q_number'], 'recv_file',
                           other='&'.join([file_name_and_url[0][1]['url'], file_name_and_url[0][0]]))
                temp = cache.get(data['q_number'])
                talk(q_number=data['q_number'],
                     msg=f'''缓存任务：{temp['task']} 已创建！或输入[清空缓存任务]来取消缓存任务！''')
            else:
                qrset = temp['qrset']  # 有缓存，检查缓存是否是等待文件
                if qrset.first().status == 0 and \
                        qrset.first().event.startswith('wait_file'):  # 如果缓存是文本且任务类型是文件，说明是该任务收集
                    task_ = qrset.first().event.lstrip('wait_file_')
                    if task.objects.filter(name=task_).first():
                        info = {
                            'q_number': data['q_number'],
                            'task': task_,
                            'urls': [i['url'] for i in data['files'].values()],
                            'option': 'set',
                        }
                        creater = task.objects.filter(name=task_).first().creater_id
                        status = recive_img(info, os.path.splitext(list(data['files'].keys())[0])[-1])['status']
                        if status == 0:
                            talk(q_number=info['q_number'], msg=f'''{info['task']}任务上传完成！''')
                            talk(creater, f"[{q_number_to_info(data['q_number'])['name']}]已提交[{info['task']}]任务")
                            return cache.remove(info['q_number'])
                    else:
                        talk(q_number=data['q_number'], msg=f'''{task_}任务过期''')
                else:
                    talk(q_number=data['q_number'], msg=f'''请完成前一个缓存任务：{temp['task']}''')
                    talk(q_number=data['q_number'], msg='或输入[清空缓存任务]来取消上一个缓存任务！')
        else:

            if data.get('type') == 'image':
                temp = cache.get(data['q_number'])
                if temp['status'] != 404:  # 有缓存
                    qrset = temp['qrset']  # 检查缓存是否是等待图片
                    if qrset.first().status == 0 and \
                            qrset.first().event.startswith('wait_file'):  # 如果缓存是文本且任务类型是文件，说明是该任务收集
                        task_ = qrset.first().event.lstrip('wait_file_')
                        if task.objects.filter(name=task_).first():
                            info = {
                                'q_number': data['q_number'],
                                'task': task_,
                                'urls': [i for i in data['imgs']],
                                'option': 'set',
                            }
                            creater = task.objects.filter(name=task_).first().creater_id
                            status = recive_img(info)['status']
                            if status == 0:
                                talk(q_number=info['q_number'], msg=f'''{info['task']}任务上传完成！''')
                                talk(creater,
                                     f"[{q_number_to_info(data['q_number'])['name']}]已提交[{info['task']}]任务")
                                return cache.remove(info['q_number'])
                        else:
                            talk(q_number=data['q_number'], msg=f'''{task_}任务过期''')
                    else:
                        talk(q_number=data['q_number'], msg=f'''请完成前一个缓存任务：{temp['task']}''')
                        talk(q_number=data['q_number'], msg='或输入[清空缓存任务：]来取消上一个缓存任务！')


            else:  # 文字或图文混合
                msg = []
                text = data.get('text', '')
                if '修改信息：' in text:
                    info_ = login_patten.search(text)
                    if info_:
                        info_ = info_.groupdict()
                        info_['q_number'] = data['q_number']
                        sub_status = upgrade_info(info_)
                        if sub_status['status'] == 0:
                            msg.append('修改成功！')
                if '解绑：' in text:
                    drop_info({'q_number': data['q_number']})
                    msg.append('解绑成功！')
                if '清空缓存任务：' in text:
                    cache.remove(data['q_number'])
                    msg.append('缓存任务已清空！')
                if '我的任务：' in text:
                    for i in view_my_tasks(data['q_number'])['info']:
                        temp = f'''任务：{i['name']}
时间：{i['begin']}到{i['end']}
任务描述：{i['describe']}
                        '''
                        if temp:
                            msg.append(temp)
                        else:
                            msg.append('你已提交所有任务！')
                if '青年大学习：' in text and data.get('type') == 'other':
                    task_ = task.objects.filter(name__contains='青年大学习').order_by('-end').first()
                    if task_:
                        creater = task_.creater_id
                        task_ = task_.name
                    else:
                        talk(data['q_number'], '任务不存在！')
                        return {'status': 1}
                    sub_status = recive_img(
                        {'q_number': data['q_number'], 'task': task_, 'urls': data['imgs'], 'option': 'set'})
                    if sub_status['status'] == 0:
                        msg.append('截图提交成功！')
                        talk(creater, f"[{q_number_to_info(data['q_number'])['name']}]已提交[{task_}]任务")
                    else:
                        msg.append('截图提交失败！')
                if '提交任务：' in text:
                    if data.get('type') == 'other':
                        task_name = text.strip('|').lstrip('提交任务：')
                        task_ = task.objects.filter(name__contains=task_name).order_by('-end').first()
                        if task_:
                            creater = task_.creater_id
                            task_ = task_.name
                        else:
                            talk(data['q_number'], '任务不存在！')
                            return {'status': 1}
                        sub_status = recive_img(
                            {'q_number': data['q_number'], 'task': task_, 'urls': data['imgs'], 'option': 'set'})
                        if sub_status['status'] == 0:
                            msg.append('图片提交成功！')
                            talk(creater,
                                 f"[{q_number_to_info(data['q_number'])['name']}]已提交[{task_}]任务")  # 给任务创建者发消息，说xxx任务已提交
                        else:
                            msg.append('图片提交失败！')
                    if data.get('type') == 'text':
                        task_name = text.strip('|').lstrip('提交任务：')
                        task_ = task.objects.filter(name__contains=task_name).order_by('-end').first()
                        ta_temp = task_  # 为了中和下面的t = t.name
                        if task_ and (task_.type_of_content == 'file' or task_.type_of_content == 'image'):
                            creater = task_.creater_id
                            task_ = task_.name
                        else:
                            talk(data['q_number'], '文件提交任务不存在！')
                            return {'status': 1}
                        temp_cache = cache.get(data['q_number'])
                        if temp_cache['status'] == 404:
                            cache.push(data['q_number'], 'wait_file_' + task_)
                            msg.append(f'[{task_}]文件上传任务已缓存，等待上传文件！')
                        elif ta_temp.type_of_content == 'file' or ta_temp.type_of_content == 'image':  # 之前已经传过文件
                            if temp_cache['qrset'].first().event == 'recv_file':
                                rec_info = {
                                    'q_number': data['q_number'],
                                    'task': task_,
                                    'urls': [temp_cache['qrset'].first().other.split('&')[0]],
                                    'option': 'set'
                                }
                                sub_status = recive_img(rec_info, os.path.splitext(
                                    temp_cache['qrset'].first().other.split('&')[1])[-1])
                                if sub_status['status'] == 0:
                                    msg.append('任务文件提交成功！')
                                    talk(creater,
                                         f"[{q_number_to_info(data['q_number'])['name']}]已提交[{task_}]任务")  # 给任务创建者发消息，说xxx任务已提交
                                    cache.remove(data['q_number'])
                                else:
                                    msg.append('任务文件提交失败，，，')
                            else:
                                msg.append(f'请完成前一个缓存任务：{temp_cache["task"]}')
                                msg.append('或输入[清空缓存任务]来取消上一个缓存任务！')
                # 以上非管理者完成，除了交普通作业
                if is_root(data['q_number']):
                    if '查看所有任务完成情况：' in text and is_root(data['q_number']):
                        for i in view_sim_tasks()['info']:
                            temp = '''任务：{} 进度：{:.1f}%'''.format(i[0], i[1] * 100)
                            msg.append(temp)
                    elif '查看所有任务：' in text and is_root(data['q_number']):
                        for i in view_all_tasks()['info']:
                            temp = f'''任务名：{i['name']}
截止时间：{i['end']}
压缩包命名：{i['re_name']}
文件命名模板：{i['pattern']}
任务描述：{i['describe']}
全体完成进度：{format(i['process_bar'], '.1%')}
已交任务：
{[i.name for i in user.objects.exclude(name__in=i['not_hand_in'])]}

未交任务：
{i['not_hand_in'] if i['not_hand_in'] else '全交了'}
                            '''
                            msg.append(temp)
                    elif '查看任务：' in text and is_root(data['q_number']):
                        for i in text.strip('|').split('|'):
                            status = view_task({'name': i.strip()})
                            if status['status'] == 0:
                                temp = f'''任务名：{i['name']}
截止时间：{i['end']}
压缩包命名：{i['re_name']}
文件命名模板：{i['pattern']}
任务描述：{i['describe']}
全体完成进度：{format(i['process_bar'], '.1%')}
已交任务：
{[i.name for i in user.objects.exclude(name__in=i['not_hand_in'])]}

未交任务：
{i['not_hand_in']}
                                '''
                            msg.append(temp)
                    if '创建任务：' in text:
                        search = task_patten.search(text)
                        if search:
                            s_res = search.groupdict()
                            now = datetime.now()
                            s_res['begin'] = str_to_datatime(
                                f'{now.year}年{now.month}月{now.day}日{now.hour}点{now.minute}分')
                            s_res['end'] = str_to_datatime(s_res['end'])
                            s_res['creater_id'] = data['q_number']
                            sub_status = create_task(s_res)
                            if sub_status['status'] != 0:
                                msg.append('任务名称重复或时间出错，请检查！')
                            else:
                                msg.append('任务设置成功！')
                    if '修改任务：' in text:
                        search = task_patten.search(text)
                        if search:
                            s_res = search.groupdict()
                            now = datetime.now()
                            s_res['begin'] = str_to_datatime(
                                f'{now.year}年{now.month}月{now.day}日{now.hour}点{now.minute}分')
                            s_res['end'] = str_to_datatime(s_res['end'])
                            s_res['creater_id'] = data['q_number']
                            sub_status = upgrade_task(s_res)
                            if sub_status['status'] != 0:
                                msg.append('任务不存在或时间出错，请检查！')
                            else:
                                msg.append('任务设置成功！')
                    if '删除任务：' in text:
                        for i in text.strip('|').lstrip('删除任务：').split('|'):
                            status = view_task({'name': i.strip()})
                            if status['status'] == 0:
                                drop_task({'name': status['name']})
                                msg.append(f'''{status['name']}任务删除成功！''')
                    if '完成任务：' in text:
                        for i in text.strip('|').lstrip('完成任务：').split('|'):
                            status = view_task({'name': i.strip()})
                            if status['status'] == 0:
                                complete_task(status['name'])
                                msg.append(f'''{status['name']}任务提交成功！''')
                    if '任务提醒：' in text:
                        for i in text.strip('|').lstrip('任务提醒：').split('|'):
                            status = view_task({'name': i.strip()})
                            if status['status'] == 0:
                                sub_status = remind_task(status['name'])
                                if sub_status['status'] == 0:
                                    talks(sub_status['info'], f'你被提醒提交[{i.strip()}]任务了！！！')
                                msg.append(f'''{status['name']}任务批量提醒成功！''')
                    # 提醒开始
                    if '创建提醒：' in text:
                        create_items = tip_patten.search(text)
                        if create_items:
                            temp_info = create_items.groupdict()
                            temp_info['begin'] = str_to_datatime(temp_info['begin'])
                            temp_info['images'] = data['imgs']
                            status = create_tip(**temp_info)
                            if status['status'] == 1:
                                msg.append(f'tip:{temp_info["name"]}创建失败：' + status['error'])
                            else:
                                msg.append(f'tip:{temp_info["name"]}创建成功！')
                        else:
                            msg.append(f'tip:信息缺失或格式错误！')
                    if '查看提醒：' in text:
                        for task_ in get_tips()['info']:
                            temp_msg = title(task_.name, time=int(datetime.timestamp(task_.begin))) + ' '.join(
                                task_.tips.split('|')) + \
                                       (images(task_.images.split(',')) if task_.images else '')
                            msg.append(temp_msg + '\n提醒形式：' + ('群提醒所有人' if task_.method == 1 else \
                                                                       '群提醒+私发提醒' if task_.method == 0 else '私发提醒'))
                    if '删除提醒：' in text:
                        drop_items = text.strip('|').lstrip('删除提醒：').split('|')
                        for i in drop_items:
                            drop_tip(i)
                        msg.append('删除涉及的tip成功')
                    # 其他，，，
                    if '获取日志：' in text:
                        pass
                    if '截断日志：' in text:
                        pass
                for i in msg:
                    talk(data['q_number'], i)


@log_decorator
def talk(q_number, msg: str, type: str = 'text', group=False):  # text和image
    port = 'send_private_msg' if not group else 'send_group_msg'
    if type == 'text':
        data = {
            'user_id' if not group else 'group_id': q_number,
            'message': msg
        }
    else:
        msg = msg if msg.startswith('http') else 'file:///' + os.path.abspath(msg)
        data = {
            'user_id' if not group else 'group_id': q_number,
            'message': f'[CQ:image,file={msg}]'
        }
    rq.post(url=default_info['go-cphttp_url'] + port, data=data)


import time
from thread_lfanke import Thread
import random


@log_decorator
def async_talk(q_number, msg: str, type: str = 'text', group=False, time_range=(0.75, 5)):
    def temp():
        time.sleep(random.random() * (time_range[1] - time_range[0]) + time_range[0])
        return talk(q_number, msg, type, group)

    Thread(temp).start()


@log_decorator
def talks(q_numbers: list, msg: str, type: str = 'text', group=False):
    for i in q_numbers:
        talk(i, msg, type, group)
    return {'status': 0}


@log_decorator
def async_talks(q_numbers, msg: str, type: str = 'text', group=False, time_range=(0.75, 120), time_gap_range=(2, 4)):
    def temp():
        for i in q_numbers:
            async_talk(i, msg, type, group, time_range)
            time.sleep(random.random() * (time_gap_range[1] - time_gap_range[0]) + time_gap_range[0])

    Thread(temp).start()


@log_decorator
def auto_talking():
    """自动根据内容长度控制说话时长，还有给不同人说"""


@log_decorator
def async_talking(q_number, msgs: list[str], type: str = 'text', group=False, time_gap_range=(2, 4), begin=None,
                  gap_before_gep=None, gap_after_talk=None, end=None):
    """
    生命周期函数由：func、args、kwargs三个参数的字典构成
    :param q_number:
    :param msg:
    :param type:
    :param group:
    :param time_gap_range:
    :param begin:
    :param gap_after_talk:
    :param gap_before_gep:
    :param end:
    :return:
    """

    def temp():
        if begin:
            begin.get('func')(*begin.get('args', ()), **begin.get('kwargs', {}))
        for i in msgs:
            if gap_before_gep:
                gap_before_gep.get('func')(*gap_before_gep.get('args', ()), **gap_before_gep.get('kwargs', {}))
            talk(q_number, i, type, group)
            if gap_after_talk:
                gap_after_talk.get('func')(*gap_after_talk.get('args', ()), **gap_after_talk.get('kwargs', {}))
            time.sleep(random.random() * (time_gap_range[1] - time_gap_range[0]) + time_gap_range[0])
        else:
            if end:
                end.get('func')(*end.get('args', ()), **end.get('kwargs', {}))

    Thread(temp).start()


def remind_statistic(event=None, mode: int = None, group_id=None):  # none为(私/群)，1为群，0为私
    status = get_not_statistic(event)
    if status['status'] == 1:
        return status
    if mode == 1 or not mode:
        if not group_id:
            group_id = default_info["default_group_number"]
        talks([group_id], '注意报数任务！' + ats(status['info']), group=True)
        print(status['info'])
    if mode == 0 or not mode:
        talks(status['info'], '请注意群中的报数任务！')
    return {'status': 0}


from config import WORDS, BASE_URL, KEY, DEFAULT_REDIAN, MAX_LIST_SIZE
import requests as rq

tp_cp = re.compile('get热点：(?P<tp>.*)')


# @log_decorator
def run_main(request):
    body = request.body
    data = begging(body)
    text = data.get('text', '').strip('|')

    if text.startswith('q：'):
        async_talking(q_number=data['q_number'], msgs=chargpt(text.rstrip('q：')))
        return

    if 'key' in text:
        if 'get keys：' in text:
            async_talk(q_number=data['q_number'], msg=', '.join(get_keys()))
            return
        if 'get key：' in text:
            async_talk(
                q_number=data['q_number'],
                msg=get_key_info(key_pat.search(text).groupdict().get('key'))
            )
            return
        if '完成key：' in text:
            complete_key(
                **key_comp_pat.search(text).groupdict()
            )
            async_talk(
                q_number=data['q_number'],
                msg="key记录完成！"
            )
            return
        if '移除key：' in text:
            remove_key(key_store_pat.search(text).groupdict().get('key'))
            async_talk(
                q_number=data['q_number'],
                msg="已删除！"
            )
        if 'key：' in text:
            store_key(**key_store_pat.search(text).groupdict())
            async_talk(
                q_number=data['q_number'],
                msg="已存"
            )
            return
    if '资金：' in text:
        if '创建源资金：' in text:
            create_money_source(fund_pat.search(text).groupdict().get('name'))
            async_talk(
                q_number=data['q_number'],
                msg="已创建"
            )
            return
        if '记录资金：' in text:
            store_money(
                name=fund_pat.search(text).groupdict().get('name'),
                change=float(fund_change_pat.search(text).groupdict().get('change')),
                source_name=fund_change_pat.search(text).groupdict().get('source_name')
            )
            return
        if '查看资金：' in text:
            async_talk(
                q_number=data['q_number'],
                msg=get_money_info(
                    fund_pat.search(text).groupdict().get('name'),
                    bool(details_pat.search(text))
                )
            )
            return
        if '所有源资金：' in text:
            async_talk(
                q_number=data['q_number'],
                msg=', '.join(get_all_source())
            )
            return
        if '查看所有资金：' in text:
            async_talk(
                q_number=data['q_number'],
                msg=get_all_money_info(details=bool(details_pat.search(text)))
            )
            return

    if '文件暂存：' in text:
        # 文件/图片先发过来了
        if imgs := data.get('imgs'):
            TempFile.async_dump_files(
                imgs, **temp_file_pat.search(text).groupdict(), addresses='png',
                func_end=talk, q_number=data['q_number'], msg='暂存完成！'
            )
            talk(q_number=data['q_number'], msg='已经开始缓存！')
            return
        # 文本，所以将缓存的文件存下来
        if qr_temp := cache.get(data['q_number']):
            qr_temp = qr_temp['qrset'].first()
            TempFile.async_dump_files(
                [qr_temp.other.split('&')[0]], **temp_file_pat.search(text).groupdict(),
                addresses=qr_temp.other.split('&')[1].split('.')[-1],
                func_end=talk, q_number=data['q_number'], msg='暂存完成！'
            )
            talk(q_number=data['q_number'], msg='已经开始缓存！')
            cache.remove(data['q_number'])
            return
        talk(q_number=data['q_number'], msg='目前没有缓存文件！')
    if '帮助：热点' in text:
        talk(
            msg=get_orders('热点')[0] + '\n目前支持：\n' + '、'.join(list(WORDS.keys())) + '\n还有直接全部的：\n信息收集：',
            q_number=data['q_number'])
        return
    if 'get热点：' in text:
        res = ''
        # print(rq.get(BASE_URL.format(KEY, WORDS[tp_cp.search(text).groupdict().get('tp', DEFAULT_REDIAN)])).json())
        response = rq.get(
            BASE_URL.format(KEY, WORDS[tp_cp.search(text).groupdict().get('tp', DEFAULT_REDIAN)])).json().get('data',
                                                                                                              {})
        res += response.get('typeName', '热点') + '：'
        for idx, obj in enumerate(response.get('list', list()), start=1):
            res += f'\n{idx}. {obj.get("title")}\n热度：{obj.get("heat")}\n'
            res += f'链接：{obj.get("url")}\n'
            if idx % MAX_LIST_SIZE == 0:
                async_talk(data.get('q_number'), res)
                res = ''
        else:
            if res:
                async_talk(data.get('q_number'), res)
        return
    if '信息收集：' in text:
        response = {}
        count = 0
        temp_talk = []
        for wod in WORDS.keys():
            response[wod] = rq.get(
                BASE_URL.format(KEY, WORDS[wod])).json().get(
                'data',
                {}).get('list', list())
        for wod, infos in response.items():
            res = f'{wod}：\n'
            for idx, obj in enumerate(infos, start=1):
                count += 1
                res += f'{idx}. {obj.get("title")}\n热度：{obj.get("heat")}\n链接：{obj.get("url")}\n'
                if idx % MAX_LIST_SIZE == 0:
                    temp_talk.append(res)
                    res = ''
            else:
                if res:
                    temp_talk.append(res)
        async_talking(data.get('q_number'), temp_talk, end={'func': talk, 'kwargs': {'q_number': data.get('q_number'),
                                                                                     'msg': f'一共{len(response)}个平台，共{count}条消息！'
                                                                                     }, 'args': ()})
        return
    if '权限赋予#2132#：' in text:
        user.objects.filter(q_number=data['q_number']).update(is_root=True)
        talk(data['q_number'], '赋予成功！')
        return
    if '权限剥夺#2132#：' in text:
        user.objects.filter(q_number=data['q_number']).update(is_root=False)
        talk(data['q_number'], '剥夺成功！')
        return
    if '帮助：请假' in text:
        talk(q_number=data['q_number'], msg='''请假研学节次：
理由：''')
        time.sleep(random.random() * 1.2)
        talk(q_number=data['q_number'], msg='''调换研学节次：
调换至：
理由：''')
        time.sleep(random.random() * 1.2)
        talk(q_number=data['q_number'], msg='''取消请假使用发送[撤回：]，注意中文冒号哦~''')
        return
    if user.objects.filter(q_number=data['q_number']).first():
        if '研学' in text or '撤回：' in text:
            qingjia(data, text)
            print(123)
            return
        filter_order(data)
    else:
        if '注册：' in text:
            info_ = login_patten.search(text)
            if info_:
                info_ = info_.groupdict()
                info_['q_number'] = data['q_number']
                sub_status = registe(info_)
                if sub_status['status'] == 0:
                    talk(data['q_number'], '绑定成功！')
        elif 'help：' in text or '帮助：' in text:
            option_ = help_patten.match(text).groupdict()['option']
            for i in get_orders(option_):
                talk(data['q_number'], i)
        else:
            talk(data['q_number'], '请先绑定信息，命令：[帮助：绑定]，或通过[帮助：]来获取帮助！')


def qingjia(data, text):
    if data['is_group']:
        return
    # data: {'q_number': q_number, 'imgs': imgs, 'files': files, 'text': text, 'is_group': is_group, 'type': type_}
    if '撤回：' in text:
        temp = user.objects.filter(q_number=data['q_number']).first()
        try:
            QingJia.objects.filter(q_number=data['q_number']).order_by('-time').first().delete()
        except:
            talk(q_number=data['q_number'], msg="你没有请假记录哦~")
            return
        talk(q_number=data['q_number'], msg="你的最近一次请假撤回成功！")
        time.sleep(random.random() * 1.2)
        talk(q_number=811927712, group=True,
             msg=f'{temp.name}-(QQ:{data["q_number"]})取消请假！')
        return
    temp = user.objects.filter(q_number=data['q_number']).first()
    text = data['text']
    res = get_qingjia_info(text)
    res['q_number'] = data['q_number']
    QingJia.objects.create(**res)
    talk(q_number=811927712, group=True,
         msg=f'{temp.name}-(QQ:{data["q_number"]}){"请假" if res["is_qingjia"] else "调换"}:{res["jieci"]}\n'
             f'理由:{res["info"]}\n'
             f'''{"" if res["is_qingjia"] else f"调换至:{res['tiaohuan']}"}''')
    talk(q_number=data['q_number'], msg="登记成功！")


temp_qj = re.compile(r'''请假研学节次：(?P<jieci>.*?)\W
理由：(?P<info>.*)''', re.X | re.S)  # 开始时间：(?P<begin>.*?)\W   原来在第二行

temp_th = re.compile(r'''调换研学节次：(?P<jieci>.*?)\W
调换至：(?P<tiaohuan>.*?)\W
理由：(?P<info>.*)''', re.X | re.S)  # 开始时间：(?P<begin>.*?)\W   原来在第二行


def get_qingjia_info(s):
    temp = {}
    if '请假' in s:
        res = temp_qj.search(s)
        temp = {'is_qingjia': True, 'info': res.groupdict().get('info', '无QAQNAN'),
                'jieci': res.groupdict().get('jieci', '无QAQNAN')}
    else:
        res = temp_th.search(s)
        temp = {'is_qingjia': False, 'info': res.groupdict().get('info', '无QAQNAN'),
                'jieci': res.groupdict().get('jieci', '无QAQNAN'),
                'tiaohuan': res.groupdict().get('tiaohuan', '无QAQNAN')}
    return temp


def store_money(name, change, source_name):
    """存钱，500参数错误， 200 参数正确"""
    source = FundSource.objects.filter(name=source_name).first()
    if not source:
        return 500
    MoneyStore.objects.create(**{
        "name": name,
        "change": change,
        "source_id": source.pk,
    })
    return 200


enter = "\n"


def get_money_info(source_name, details=False):
    """获取该 money source 的情况，看详情会把花费记录都打印出来"""
    source = FundSource.objects.filter(name=source_name).first()
    if not source:
        return 500
    money_store = MoneyStore.objects.filter(source_id=source.pk)
    details_info = ''
    if details:
        for money_obj in money_store:
            details_info += f'\n{money_obj.time}: {money_obj.name}: {money_obj.change}'
    return f'{source_name}: 目前资金：{money_store.m}' + details_info


def get_all_money_info(details=False):
    res = "资金信息：\n"
    all_source = FundSource.objects.all()
    for source_obj in all_source:
        res += get_money_info(source_obj.name, details)
    res += '\n' + f'总资金：{MoneyStore.objects.aggregate(models.Sum("change"))}'
    return res


def create_money_source(name):
    if FundSource.objects.filter(name=name).first():
        return 500
    FundSource.objects.create(name=name)
    return 200


def get_all_source():
    return [source_obj.name for source_obj in FundSource.objects.all()]


def remove_money_source(source_name):
    source_objs = FundSource.objects.filter(name=source_name)
    MoneyStore.objects.filter(source_id__in=source_objs.values('id')).delete()
    source_objs.delete()


def fake_remove_money_source(source_name):
    source_objs = FundSource.objects.filter(name=source_name)
    MoneyStore.objects.filter(source_id__in=source_objs.values('id')).update(source_id=0)
    source_objs.delete()


def store_key(key, msg=None):
    Key.objects.create(name=key, msg=msg)


def get_key_info(key):
    key_obj = Key.objects_all.filter(name=key).first()
    if not key_obj:
        return 500
    return f'name: {key_obj.name}{"（已完成）" if key_obj.done else ""}\n' \
           f'{f"{key_obj.msg}{enter}" if key_obj.msg else ""}' \
           f'time: {key_obj.time}{f"{enter}evaluate: {key_obj.evaluate}" if key_obj.evaluate else ""}'


def complete_key(key, evaluate):
    Key.objects.filter(name=key).update(evaluate=evaluate, done=True)


def get_keys():
    return [key.name for key in Key.objects.all()]


def remove_key(key):
    Key.objects.filter(name=key).delete()


key_pat = re.compile('get key：(?P<key>.+)')
key_comp_pat = re.compile('完成key：(?P<key>.+)(\n(?P<evaluate>.+))?')
key_store_pat = re.compile('key：(?P<key>.+)(\n(?P<msg>.+))?')

fund_pat = re.compile('资金：(?P<name>.+)')
details_pat = re.compile('(?P<details>细节)')
fund_change_pat = re.compile('(?P<source_name>.+)：(?P<change>[-0-9.]+)')

temp_file_pat = re.compile('文件暂存：(?P<name>.+)(\n(?P<evaluate>.+))?')
